import { makeAutoObservable, runInAction } from 'mobx'
import type { DetailType, UserInfoType } from './interface'
import { getData, postData, putData } from '@/servers/http'
import { history } from 'umi'
import { api } from '@/servers/api'
import { Dialog, Toast } from 'antd-mobile'
import dayjs from 'dayjs'
import { setUserCenterCookies } from '@/utils/userCenter'
import { SourceEnum, TrainEnum } from '@/const'
import { isNullData } from '@/utils'
import { getLocalStorage, setLocalStorage } from '@/storage'

class Store {
    /** 档案详情 */
    public fileDetail: Partial<DetailType> = {}
    /** 用户信息 */
    public userInfo: Partial<UserInfoType> = {}
    /** 加载状态 */
    public loading = false

    constructor() {
        makeAutoObservable(this)
    }
    /** 获取档案详情 */
    getFileDetail = () => {
        this.loading = true
        const { id } = history.location.query || {}
        getData(`${api.userBarriersById}${id}`)
            .then(({ status, data }) => {
                if (status === 200 && data) {
                    runInAction(() => {
                        this.fileDetail = data || {}
                    })
                }
            })
            .finally(() => {
                this.loading = false
            })
    }
    /** 获取用户信息 */
    getUserInfo = () => {
        getData(api.usersLoginUserInfo).then(({ status, data }) => {
            if (status === 200 && data) {
                runInAction(() => {
                    this.userInfo = data || {}
                })
            }
        })
    }
    /** 点击操作按钮 */
    clickOperation = (type: number, callback: () => void) => {
        const identityType = getLocalStorage('IDENTITY_TYPE')
        if (Number(identityType) === 2) {
            if (type === SourceEnum.FILL_IN_ONLINE) {
                if (this.fileDetail.is_finished === '1') {
                    Dialog.confirm({
                        content: '档案已完成，是否要重新编辑',
                        confirmText: '继续',
                        onConfirm: () => {
                            setLocalStorage('ARCHIVE_DETAIL_SOURCE', type)
                            callback()
                        },
                    })
                } else {
                    setLocalStorage('ARCHIVE_DETAIL_SOURCE', type)
                    callback()
                }
            } else {
                if (this.fileDetail.id === '16') {
                    setLocalStorage('ARCHIVE_DETAIL_SOURCE', type)
                    this.jumpJobList()
                    return
                }
                setLocalStorage('ARCHIVE_DETAIL_SOURCE', type)
                callback()
            }
        } else {
            getData(api.userBarriersScoreInfo).then(({ data: scoreInfo }) => {
                if (Number(scoreInfo?.is_score) === 1) {
                    Toast.show(Number(scoreInfo?.is_course_score) === 1 ? '讲师已评分' : '讲师已评审')
                    return
                } else {
                    // 结班时间
                    if (dayjs().isAfter(dayjs(scoreInfo.end_time).endOf('day'))) {
                        Toast.show('当前已结束培训')
                        return
                    }
                    if (type === SourceEnum.FILL_IN_ONLINE) {
                        if (this.fileDetail.is_finished === '1') {
                            Dialog.confirm({
                                content: '档案已完成，是否要重新编辑',
                                confirmText: '继续',
                                onConfirm: () => {
                                    setLocalStorage('ARCHIVE_DETAIL_SOURCE', type)
                                    callback()
                                },
                            })
                        } else {
                            setLocalStorage('ARCHIVE_DETAIL_SOURCE', type)
                            callback()
                        }
                    } else {
                        if (this.fileDetail.id === '16') {
                            setLocalStorage('ARCHIVE_DETAIL_SOURCE', type)
                            this.jumpJobList()
                            return
                        }
                        setLocalStorage('ARCHIVE_DETAIL_SOURCE', type)
                        callback()
                    }
                }
            })
        }
    }
    /** 档案16  完成我的岗位匹配表 实训同步 跳转职位列表页面*/
    jumpJobList = () => {
        const identityType = getLocalStorage('IDENTITY_TYPE')
        const { platform_access_token, mid_domain, platform_site_id = '', imitate_site_id = '', platform_site_alias, imitate_site_alias, platform_usercode } = this.userInfo || {}
        setUserCenterCookies(
            {
                h5Token: platform_access_token,
                h5SelectUserType: '1',
                h5UserCode: platform_usercode,
                h5Alias: Number(identityType) === 2 ? imitate_site_alias : platform_site_alias,
            },
            Number(identityType) === 2 ? imitate_site_id : platform_site_id,
        )
        window.location.href = `${mid_domain}/job-center/job/list?from=trainingSync&dossierId=${this.fileDetail.id}`
    }
    /** 在线填写 */
    fillInOnline = () => {
        const identityType = getLocalStorage('IDENTITY_TYPE')
        const { platform_access_token, mid_domain, platform_site_id = '', imitate_site_id = '', platform_site_alias, imitate_site_alias, platform_usercode } = this.userInfo || {}
        const { id, code, detail } = this.fileDetail || {}
        let callbackUrl = ''
        callbackUrl = encodeURIComponent(window.location.origin + `/#/archivemiddle?id=${id}&questionnaireCode=${code}`)
        setUserCenterCookies(
            {
                h5Token: platform_access_token,
                h5SelectUserType: '1',
                h5UserCode: platform_usercode,
                h5Alias: Number(identityType) === 2 ? imitate_site_alias : platform_site_alias,
            },
            Number(identityType) === 2 ? imitate_site_id : platform_site_id,
        )
        window.location.href = `${mid_domain}/question-center/collecting?code=${code}&h5Back=${callbackUrl}&fill=edit` + (detail?.code ? `&collectCode=${detail?.code}` : '')
    }
    /** 实训同步接口 */
    trainInterface = async () => {
        let res
        if (this.fileDetail.is_finished === '1') {
            res = await putData(`${api.userBarriersBatchUpdate}${this.fileDetail.id}`, { fill_type: 3 })
        } else {
            res = await postData(`${api.userBarriersBatchInput}${this.fileDetail.id}`, { fill_type: 3 })
        }
        if (res.status === 200) {
            Toast.show({ icon: 'success', content: '实训同步成功' })
            this.getFileDetail()
        }
        if (res.status === 204) {
            this.showUnfinishedModal()
        }
    }
    /** 未完成实训时展示弹窗 */
    showUnfinishedModal = () => {
        const userData = getLocalStorage('USER_DATA')
        const { mid_domain, platform_access_token } = userData || {}
        Dialog.confirm({
            content: '还未完成实训',
            confirmText: '前往实训',
            onConfirm: () => {
                let url = ''
                switch (this.fileDetail.type) {
                    case TrainEnum.FIVE_FINGER:
                        url = `/careerredact?id=${this.fileDetail.id}`
                        break
                    case TrainEnum.RAINBOW:
                        url = `/rainbow?id=${this.fileDetail.id}`
                        break
                    case TrainEnum.INTENTION_POST:
                        const callbackUrl = encodeURIComponent(window.location.origin + `/#/archivedetail?id=${this.fileDetail.id}`)
                        window.location.href = `${mid_domain}/job-center/intended-position/index?token=${platform_access_token}&callback=${callbackUrl}&openKey=`
                        return
                    default:
                        break
                }
                if (url) {
                    history.push(url)
                }
            },
        })
    }
    clearData = () => {
        this.fileDetail = {}
        this.userInfo = {}
        this.loading = false
    }
}

export default new Store()
